package com.fizy.client.methods;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.fizy.client.enums.Operation;

public class FizyMethods {
	private final String END_POINT = "https://api.fizy.com";

	public String call(Operation operation, String... params) throws Exception {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		// HttpGet getRequest = new HttpGet("https://api.fizy.com/v1/moods");
		//		HttpGet getRequest = new HttpGet("https://api.fizy.com/v1/tracks/1");
		//		HttpGet getRequest = new HttpGet("https://api.fizy.com/v1/search");
		String url = END_POINT + operation.getUrlPattern();

		for (String param : params) {
			url += param;
		}

		HttpGet getRequest = new HttpGet(url);
		getRequest.addHeader("accept", "application/json");
		String credentials = "test" + ":" + "k7t7Yk..RsadRWzzV?vkhkHFNrR";
		String encodedAuth = "Basic " + new String(Base64.encodeBase64(credentials.getBytes("UTF-8")), "UTF-8");
		getRequest.addHeader("Authorization", encodedAuth);
		HttpResponse response = httpClient.execute(getRequest);

		if (response.getStatusLine().getStatusCode() != 200) {
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
		}

		BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

		StringBuilder sb = new StringBuilder();
		String line;
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		httpClient.getConnectionManager().shutdown();
		String output = sb.toString();
		return output;
	}
}
